﻿using DevExpress.Mvvm;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VGTimer.Models
{
    /// <summary>
    /// 表示一路信号，包括开关状态，电压，电流
    /// </summary>
    public class Device : BindableBase
    {
        public Device()
        {
            CountDownCommand = new DelegateCommand<double>(CountDown);
        }

        private async void CountDown(double value)
        {
            if (value <= 0)
            {
                return;
            }

            if (!IsCountDown)
            {
                IsCountDown = true;
                RemainingTime = TimeSpan.FromHours(value);
                while (RemainingTime > TimeSpan.Zero)
                {
                    await Task.Delay(1000);
                    RemainingTime = RemainingTime.Subtract(TimeSpan.FromSeconds(1));
                }

                if (IsCountDown)
                {
                    Console.Beep(800, 2000);
                    IsCountDown = false;
                }
            }
            else
            {
                IsCountDown = false;
            }

            RemainingTime = TimeSpan.Zero;
        }

        /// <summary>
        /// 设备编号
        /// </summary>
        [JsonProperty("Index")]
        public int Index { get { return GetValue<int>(); } set { SetValue(value); } }

        /// <summary>
        /// 设备别名
        /// </summary>
        [JsonProperty("NickName")]
        public string NickName
        {
            get { return GetValue<string>(); }
            set { SetValue(value); }
        }

        /// <summary>
        /// 设备详细描述
        /// </summary>
        [JsonProperty("Detail")]
        public string Detail
        {
            get { return GetValue<string>(); }
            set { SetValue(value); }
        }

        /// <summary>
        /// 设备类型
        /// </summary>
        [JsonProperty("DeviceType")]
        public string DeviceType
        {
            get { return GetValue<string>(); }
            set { SetValue(value); }
        }


        public Uri Image
        {
            get { return GetIcon(); }
        }

        private Uri GetIcon()
        {
            try
            {
                return new Uri($"pack://application:,,,/Images/{DeviceType}.png", UriKind.Absolute);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public DelegateCommand<double> CountDownCommand { get; set; }

        /// <summary>
        /// 计时剩余
        /// </summary>
        public TimeSpan RemainingTime { get { return GetValue<TimeSpan>(); } set { SetValue(value); } }

        /// <summary>
        /// 是否正在倒计时
        /// </summary>
        public bool IsCountDown { get { return GetValue<bool>(); } set { SetValue(value); } }
    }
}